<template>
    <div id="toAllocate">
        <!--搜索框-->
        <div class="salesman-tree">
            <div class="sava-btn">
                <el-button type="danger" class="salesman-tree-save" @click="deleteItem">删除勾选权限</el-button>
            </div>
            <el-tree
                :expand-on-click-node="true"
                :default-expanded-keys="['0000']"
                :props="defaultProps"
                ref="tree"
                :data="treeData"
                :default-expand-all="false"
                show-checkbox
                node-key="id"
                @node-click="clickTree"
            >
            </el-tree>
        </div>

        <div class="salesman-content">
            <div class="toAllocateBox">
                <h3>发布资源</h3>
                <el-form :rules="rules" :model="form_publish" ref="form_publish" label-width="100px" class="demo-ruleForm toAllocateBoxForm">
                    <el-form-item label="父资源" prop="p_name">
                        <el-input v-model="form_publish.p_name" disabled></el-input>
                    </el-form-item>

                    <el-form-item label="资源名" prop="name">
                        <el-input v-model="form_publish.name"></el-input>
                    </el-form-item>

                    <el-form-item label="资源类型" prop="region">
                        <el-select v-model="form_publish.region" placeholder="请选择活动区域" @change="showMenuIndex">
                            <el-option label="目录" value="directory"></el-option>
                            <el-option label="功能权限" value="function"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="URL" prop="url" required>
                        <el-input v-model="form_publish.url"></el-input>
                    </el-form-item>
                    <el-form-item label="静态URL" prop="url" required v-if="hasStaticUrl">
                        <el-input v-model="form_publish.staticUrl"></el-input>
                    </el-form-item>
                    <el-form-item label="排序" prop="menuIndex" v-if="hasIndex">
                        <el-input v-model="form_publish.menuIndex" placeholder="只限目录排序，越大越靠前，默认为空"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="desc">
                        <el-input type="textarea" v-model="form_publish.remark"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="publish" :disabled="isDisabled">发布</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="toAllocateBox">
                <h3>修改资源</h3>
                <el-form :model="form_edit" ref="form_edit" label-width="100px" class="demo-ruleForm toAllocateBoxForm" :rules="rules">
                    <el-form-item label="资源名" prop="name">
                        <el-input v-model="form_edit.name"></el-input>
                    </el-form-item>

                    <el-form-item label="URL" prop="">
                        <el-input v-model="form_edit.url"></el-input>
                    </el-form-item>

                    <el-form-item label="静态URL" prop="" v-if="hasStaticUrl_edit">
                        <el-input v-model="form_edit.staticUrl"></el-input>
                    </el-form-item>
                    <el-form-item label="排序" prop="menuIndex" v-if="hasIndex_edit">
                        <el-input v-model="form_edit.menuIndex" placeholder="只限目录排序，越大越靠前，默认为空"></el-input>
                    </el-form-item>
                    <el-form-item label="资源类型" prop="region">
                        <el-select v-model="form_edit.region" placeholder="请选择活动区域" disabled>
                            <el-option label="目录" value="directory"></el-option>
                            <el-option label="功能权限" value="function"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- <el-form-item label="资源状态" prop="region">
                        <el-select v-model="form_edit.status" placeholder="请选择活动区域">
                            <el-option label="上线" value="online"></el-option>
                            <el-option label="下线" value="offline"></el-option>
                        </el-select>
                    </el-form-item> -->

                    <el-form-item label="备注" prop="desc">
                        <el-input type="textarea" v-model="form_edit.remark"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="changeRes">修改</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import axo from "@/assets/js/axo";
export default {
    name: "toAllocate",
    data() {
        return {
            rules: {
                p_name: [
                    {required: true, message: '必填，请选择一个父级菜单'}
                ],
                name: [
                    {required: true, message: '必填，请输入名称'}
                ],
                url: [
                    {required: true, message: '必填，请输入URL地址', trigger: 'blur'}
                ]
            },
            hasStaticUrl: false,
            hasStaticUrl_edit: false,
            hasIndex: true,
            hasIndex_edit: true,
            isDisabled: false,
            form_publish: {
                p_name: '借款管理平台',
                name: '',
                region: 'directory',
                url: '',
                staticUrl: '',
                menuIndex: '',
                remark: ''
            },
            form_edit: {
                id: '0000',
                name: '借款管理平台',
                region: 'directory',
                type: '1',
                status: 'online',
                url: '',
                staticUrl: '',
                menuIndex: '',
                remark: ''
            },
            treeData: [{
                id: '0000',
                label: '借款管理平台',
                type: '1',
                children: [{
                    id: '',
                    label: '借款管理',
                    type: '1',
                    children: []
                }]
            }],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            activeItem: {
                id: '0000',
                label: '借款管理平台',
                type: '1',
                children: []
            }
        };
    },
    mounted () {
        this.getTreeData();
    },
    methods: {
        showMenuIndex (a) {
            if(a === 'function'){
                this.hasIndex = false;
            }else{
                this.hasIndex = true;
            }
        },
        clickTree(self, node, tree) {
            /**
             * [if description]
             * @param  {[type]} self    [该节点所对应的对象]
             * @param  {[type]} node    [节点对应的 Node]
             * @param  {[type]} tree    [节点组件本身]
             * @return {[type]}         [description]
             */
            this.activeItem = self;
            if(self.type === '1'){
                this.form_publish.p_name=self.label;
            }
            if(self.type === '1' && self.url){
                this.hasStaticUrl_edit = true;
            }else{
                this.hasStaticUrl_edit = false;
            }
            if(self.pid === '0000'){
                this.hasStaticUrl = true;
            }else{
                this.hasStaticUrl = false;
            }

            // 是否可以发布
            if(self.type === '1'){
                this.isDisabled = false;
            }else{
                this.isDisabled = true;
            }
            // 修改资源显示排序选项
            if(self.type === '1'){
                this.hasIndex_edit = true;
                if(this.form_publish.region === 'directory'){
                    this.hasIndex = true;
                }else{
                    this.hasIndex = false;
                }
            }else{
                this.hasIndex_edit = false;
            }
            this.form_edit.id = self.id;
            this.form_edit.name = self.label;
            this.form_edit.url = self.url;
            this.form_edit.staticUrl = self.staticUrl;
            this.form_edit.menuIndex = self.menuIndex;
            this.form_edit.type = self.type;
            this.form_edit.remark = self.remark;
            this.form_edit.region = (self.type === "1"?'directory':'function');
            console.log(self);
        },
        publish () {
            /**
             * 判断文件夹下是否可以添加按钮
             * @param {type: '1'}   目录
             * @param {type: '2'}   权限
             * @type {[type]} true|1可以新建目录
             *                false|2可以新建权限按钮
             *                0 可以新建目录或权限按钮
             */
            let itemType = null;
            let spbool = this.activeItem.children.every((ele,item) => {
                if(ele.type === '1'){
                    return true;
                }
                return false;
            });
            itemType = spbool?"1":"2";
            if(this.activeItem.children.length === 0){
                itemType = '0';
            }

            this.$refs.form_publish.validate((valid) => {
                if(!valid){
                    this.$message.error('请正确填写参数');
                }else{
                    if(this.form_publish.region === 'directory'){
                        if(itemType === '1' || itemType=== '0'){
                            axo({
                                method: "post",
                                url: "/api-sys/menu/add",
                                data: {
                                    "platformNo": "1",
                                    "body": {
                                        name: this.form_publish.name,
                                        url: this.form_publish.url,
                                        staticUrl: this.form_publish.staticUrl,
                                        menuIndex: this.form_publish.menuIndex,
                                        parentId: this.activeItem.id,
                                        remark: this.form_publish.remark
                                    }
                                }
                            }).then((res) => {
                                console.log(res);
                                if(res.data.state.code === '200'){
                                    this.$message({
                                        message: '新建成功',
                                        type: 'success',
                                        duration: 800
                                    });
                                    this.getTreeData();
                                }
                            });
                        }else{
                            this.$message.warning("权限列表不能再新建目录");
                        }
                    }
                    if(this.form_publish.region === 'function'){
                        if(itemType === '2' || itemType === '0'){
                            axo({
                                method: "post",
                                url: "/api-sys/menuElement/add",
                                data: {
                                    "platformNo": "1",
                                    "body": {
                                        name: this.form_publish.name,
                                        url: this.form_publish.url,
                                        remark: this.form_publish.remark,
                                        menuId: this.activeItem.id
                                    }
                                }
                            }).then((res) => {
                                console.log(res);
                                if(res.data.state.code === '200'){
                                    this.$message({
                                        message: '新建成功',
                                        type: 'success',
                                        duration: 800
                                    });
                                    this.getTreeData();
                                }
                            });
                            console.log(itemType);
                        }else{
                            this.$message.warning("目录列表不能新建功能权限");
                        }
                    }
                }
            });
            console.log(this.form_publish);
        },
        changeRes () {
            let editData = this.form_edit;
            console.log(editData);
            // console.log(this.activeItem);
            if(editData.id === '0000'){
                this.$message({
                    message: '根目录不能修改',
                    type: 'warning',
                    duration: 800
                });
                return ;
            }

            // 更改目录信息
            if(editData.type === '1'){
                axo({
                    method: "post",
                    url: "/api-sys/menu/update",
                    data: {
                        "platformNo": "1",
                        "body": {
                            id: editData.id,
                            name: editData.name,
                            url: editData.url,
                            staticUrl: editData.staticUrl,
                            menuIndex: editData.menuIndex?editData.menuIndex:'0',
                            remark: editData.remark
                        }
                    }
                }).then((res) => {
                    console.log(res);
                    if(res.data.state.code === '200'){
                        this.$message({
                            message: '修改成功',
                            type: 'success',
                            duration: 800
                        });
                        this.getTreeData();
                    }
                });
            }

            // 更改权限按钮信息
            if(editData.type === '2'){
                axo({
                    method: "post",
                    url: "/api-sys/menuElement/update",
                    data: {
                        "platformNo": "1",
                        "body": {
                            id: editData.id,
                            name: editData.name,
                            url: editData.url,
                            remark: editData.remark
                        }
                    }
                }).then((res) => {
                    console.log(res);
                    if(res.data.state.code === '200'){
                        this.$message({
                            message: '修改成功',
                            type: 'success',
                            duration: 800
                        });
                        this.getTreeData();
                    }
                });
            }
        },
        deleteItem () {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let checkedNodes = this.$refs.tree.getCheckedNodes();
                let menuStr = [];
                let eleStr = [];
                checkedNodes.forEach((ele,item) => {
                    if(ele.type==='1'){
                        menuStr.push(ele.id);
                    }
                    if(ele.type==='2'){
                        eleStr.push(ele.id);
                    }
                });
                axo({
                    method: "post",
                    url: "/api-sys/menu/del",
                    data: {
                        "platformNo": "1",
                        "body": {
                            menu: menuStr.join(","),
                            element: eleStr.join(",")
                        }
                    }
                }).then((res) => {
                    console.log(res);
                    if(res.data.state.code === '200'){
                        this.$message({
                            message: '修改成功',
                            type: 'success',
                            duration: 800
                        });
                        this.$message({
                            type: 'success',
                            message: '删除成功!',
                            duration: 800
                        });
                        this.getTreeData();
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除',
                    duration: 800
                });
            });
        },
        async getTreeData () {
            // 重置根目录树为空
            this.$refs.tree.setCheckedKeys([]);

            let treeArr = [];
            let treeList = [];
            await axo({
                method: "post",
                url: "/api-sys/menu/queryMenuTree",
                // url: "/api-sys/menu/queryMenuTreeAndCheck",
                data: {
                    "platformNo": "1",
                    "body": {}
                }
            }).then((res) => {
                treeArr = JSON.parse(res.data.ciphertext);
                console.log(JSON.parse(res.data.ciphertext));
            });
            // console.log(treeArr);
            /**
             * 遍历生成树结构函数
             * @param  {[type]} tree [要遍历的平行数组]
             * @return {[type]}      [description]
             */
            function traversal(tree,pid="0000"){
                let ye=[];

                tree.forEach((ele,index,arr) => {
                    if(ele.pid===pid && ele.type==="1"){
                        let item = {};
                        item.id = ele.id;
                        item.label = ele.name;
                        item.pid = ele.pid;
                        item.remark = ele.remark?ele.remark:"";
                        item.type = ele.type;
                        item.url = ele.url?ele.url:"";
                        item.staticUrl = ele.staticUrl?ele.staticUrl:"";
                        item.menuIndex = ele.menuIndex?ele.menuIndex:"";
                        item.children = traversal(tree,item.id);
                        ye.push(item);
                    }
                    if(ele.pid===pid && ele.type==="2"){
                        let item = {};
                        item.id = ele.id;
                        item.label = ele.name;
                        item.pid = ele.pid;
                        item.remark = ele.remark?ele.remark:"";
                        item.type = ele.type;
                        item.url = ele.url?ele.url:"";
                        ye.push(item);
                    }
                });
                return ye;
            }
            this.treeData[0].children = traversal(treeArr,"0000");
            // console.log(traversal(treeArr,"0000"));
        }
    }
};
</script>

<style lang="scss">
    #toAllocate{
        padding: 20px;
        overflow: hidden;
        .salesman-tree{
            position: relative;
            float: left;
            width: 300px;
            min-height: 80px;
            border: 1px solid #eee;
            overflow: hidden;
            .el-tree{
                border: none!important;
            }
            .sava-btn{
                text-align: right;
                .salesman-tree-save{
                    margin: 10px 15px;
                }
            }
        }
        .salesman-content{
            margin-left: 320px;
            overflow: hidden;
            .toAllocateBox{
                width: 700px;
                padding: 0px;
                border: 1px solid #eee;
                margin-bottom: 50px;
                h3{
                    border-bottom: 1px solid #eee;
                    padding: 15px;
                }
                .toAllocateBoxForm{
                    margin: 20px;
                }
            }

        }
    }
</style>
<style media="screen">
    /*修改默认样式*/
    #toAllocate .el-input.is-disabled .el-input__inner{
        color: #1f2d3d;
    }
</style>
